package com.yunwushanhe.scheduledjob;

import com.yunwushanhe.constant.RedisConstant;
import com.yunwushanhe.entity.Article;
import com.yunwushanhe.service.ArticleService;
import com.yunwushanhe.util.RedisCache;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author 抬头看看天
 * @Date 2023-08-15  16:07:58
 * 用于定时执行把浏览量定时从redis中存储到mysql数据库中的类
 */
@Component
public class UpdateSqlArticleViewCountJob {

    @Resource
    private RedisCache redisCache;

    @Resource
    private ArticleService articleService;

    @Scheduled(cron = "0/30 * * * * ?")
    public void updateArticleViewCount(){
        Map<String, Integer> viewCountMap = redisCache.getCacheMap(RedisConstant.ARTICLE_VIEWCOUNT_KEY);

        List<Article> articleList = viewCountMap.entrySet()
                .stream()
                .map(entry -> new Article(Long.parseLong(entry.getKey()),entry.getValue().longValue()))
                .collect(Collectors.toList());

        articleService.updateBatchById(articleList); // 批量更新操作
        System.out.println("===================== 对MySQL数据库进行了一次更新！=========================");
    }
}
